import { message } from 'antd';
import { downloadBlob, transformBody, transformJsonToQuery } from './index';

const BASE_URL = '/api'; // 这个API基础URL可以根据环境进行配置

// 一个处理请求的函数，返回一个Promise
async function handleRequest<T>(url: string, options?: RequestInit): Promise<T> {
  try {
    // 请求全路径
    const fullUrl = `${BASE_URL}${url}`;
    // 写入token
    let headers = {
      'Content-Type': options?.headers?.['Content-Type'] || 'application/json',
      ...options.headers,
    };
    if (!fullUrl.includes('/auth/login')) {
      const token = localStorage.getItem('cms-project-token');
      headers.Authorization = `Bearer ${token}`;
    }

    const response = await fetch(fullUrl, {
      ...options,
      headers,
    });

    if (options?.responseType === 'blob') {
      const blobData = await response.blob();
      const contentDisposition = response.headers.get('Content-Disposition');
      console.log('@@@ contentDisposition', contentDisposition);
      if (blobData) {
        try {
          downloadBlob(blobData, contentDisposition);
          message.success('操作成功');
          return { message: '操作成功' };
        } catch {
          message.error('操作失败');
          return { message: '操作失败' };
        }
      }

      message.error('操作失败');
      return { message: '操作失败' };
    }

    const data = await response.json();

    if (!response.ok) {
      message.error(data?.msg || '服务调用失败');
      return null;
    }

    return data.result;
  } catch (error) {
    message.error('服务异常:', error);
    throw error;
  }
}

// GET请求
export async function get<T>(url: string, body: object): Promise<T> {
  // 过滤字符串 去除前后空格
  const query = transformBody(body);
  // 过滤query再转成字符串
  const queryStr = query ? transformJsonToQuery(query) : '';
  // 请求路由拼接
  const queryUrl = queryStr ? `${url}?${queryStr}` : url;

  return handleRequest<T>(queryUrl, {
    method: 'GET',
  });
}

// POST请求
export async function post<T>(url: string, body: object, config): Promise<T> {
  const filterBody = body ? transformBody(body) : undefined;
  return handleRequest<T>(url, {
    method: 'POST',
    body: JSON.stringify(filterBody),
    ...config,
  });
}

// PUT请求
export async function patch<T>(url: string, body: object): Promise<T> {
  const filterBody = body ? transformBody(body) : undefined;
  return handleRequest<T>(url, {
    method: 'PATCH',
    body: JSON.stringify(filterBody),
  });
}

// DELETE请求
export async function del<T>(url: string, body: object): Promise<T> {
  const filterBody = body ? transformBody(body) : undefined;
  return handleRequest<T>(url, {
    method: 'DELETE',
    body: JSON.stringify(filterBody),
  });
}
